package com.member.mp.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.core.domain.R;
import com.member.common.core.domain.entity.SysDictData;
import com.member.common.core.page.PageResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.CollectionTypeEnum;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.utils.StringUtils;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.*;
import com.member.shop.dto.DictInfo;
import com.member.shop.service.*;
import com.member.shop.vo.MaterialVo;
import com.member.shop.vo.TenantPayVo;
import com.member.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.member.common.enums.DeleteEnum.NOT_DELETE;

/**
 * 【平台接口】控制器
 *
 * @author wangxin
 * @version 1.0
 * @date Mon Jul 03 22:06:51 CST 2024
 **/
@RestController
@Api(value = "平台接口", tags = {"平台接口"})
@RequestMapping("/wx/platform")
@Slf4j
public class PlatformController extends SupperController {
    @Resource
    private ISysBizMaterialCategoryService sysBizMaterialCategoryService;
    @Resource
    private ISysBizRecommendCategoryService recommendCategoryService;
    @Resource
    private ISysBizServiceQuestionService serviceQuestionService;
    @Resource
    private ISysBizMaterialService sysBizMaterialService;
    @Resource
    private ISysBizTenantAreaService tenantAreaService;
    @Resource
    private ISysBizProfileService sysBizProfileService;
    @Resource
    private ISysDictDataService sysDictDataService;
    @Resource
    private ISysBizTenantService tenantService;
    @Resource
    private ISysBizUserService userService;
    @Resource
    private ISysBizPopService popService;


    @RequestMapping(value = "/dictList", method = RequestMethod.GET)
    @ApiOperation(value = "获取枚举列表（所有枚举列表，app启动时缓存）")
    @ResponseBody
    public R<List<DictInfo>> dictList() {
        try {
            SysDictData sysDictData = new SysDictData();
            sysDictData.setStatus("0");
            List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictData);
            List<DictInfo> dictInfos = new ArrayList<>();
            for (SysDictData dictData : sysDictDataList) {
                DictInfo dictInfo = new DictInfo();
                BeanUtils.copyProperties(dictData, dictInfo);
                dictInfos.add(dictInfo);
            }
            return R.ok(dictInfos);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取弹屏广告列表（0：开屏）
     *
     * @param type 0：开屏
     * @return 分类列表
     */
    @GetMapping("/queryPop/{type}")
    public R<List<SysBizPop>> queryPop(@PathVariable Integer type) {
        try {
            LambdaQueryWrapper<SysBizPop> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizPop::getTenantId, getTenantId());
            queryWrapper.eq(SysBizPop::getType, type);
            queryWrapper.eq(SysBizPop::getDeleted, NOT_DELETE.getKey());
            queryWrapper.eq(SysBizPop::getDisplayed, EnableStatusEnum.ENABLE.getKey());
            queryWrapper.orderByDesc(SysBizPop::getOrderNum);
            List<SysBizPop> list = popService.list(queryWrapper);
            // 返回数据
            return R.ok(list);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取商品推荐分类失败", e);
            return R.fail("获取商品推荐分类失败，请稍后尝试");
        }
    }

    /**
     * 获取站点列表
     *
     * @return 获取列表
     */
    @GetMapping("/queryTenantList")
    public R<List<SysBizTenant>> queryTenantList() {
        try {
            LambdaQueryWrapper<SysBizTenant> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizTenant::getDeleted, NOT_DELETE.getKey());
            queryWrapper.eq(SysBizTenant::getGrounding, EnableStatusEnum.ENABLE.getKey());
            queryWrapper.orderByDesc(SysBizTenant::getOrderNum);
            List<SysBizTenant> list = tenantService.list(queryWrapper);
            // 返回数据
            return R.ok(list);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取站点列表失败", e);
            return R.fail("获取站点列表失败，请稍后尝试");
        }
    }

    /**
     * 获取默认站点
     *
     * @return 默认站点
     */
    @GetMapping("/queryDefaultTenant")
    public R<SysBizTenant> queryDefaultTenant() {
        try {
            SysBizTenant tenantByDefault = tenantService.selectSysBizTenantByDefault();
            // 返回数据
            return R.ok(tenantByDefault);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取默认站点", e);
            return R.fail("获取默认站点，请稍后尝试");
        }
    }

    /**
     * 获取站点授权城市列表
     *
     * @param tenantId 站点id
     * @return 站点授权城市列表
     */
    @GetMapping("/queryTenantAreaList/{tenantId}")
    public R<List<SysBizTenantArea>> queryTenantAreaList(@PathVariable Long tenantId) {
        try {
            LambdaQueryWrapper<SysBizTenantArea> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizTenantArea::getTenantId, tenantId);
            queryWrapper.eq(SysBizTenantArea::getDeleted, NOT_DELETE.getKey());
            queryWrapper.orderByDesc(SysBizTenantArea::getOrderNum);
            List<SysBizTenantArea> result = tenantAreaService.list(queryWrapper);
            return R.ok(result);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("查询站点授权城市列表失败", e);
            return R.fail("查询站点授权城市列表失败，请稍后尝试");
        }
    }

    /**
     * 获取商品推荐分类
     *
     * @param type 0 首页（腰封广告下） 1 分类（商品分类下）
     * @return 分类列表
     */
    @GetMapping("/queryRecommendCategory/{type}")
    public R<List<SysBizRecommendCategory>> queryRecommendCategory(@PathVariable Integer type) {
        try {
            LambdaQueryWrapper<SysBizRecommendCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizRecommendCategory::getTenantId, getTenantId());
            queryWrapper.eq(SysBizRecommendCategory::getRecommendType, type);
            queryWrapper.eq(SysBizRecommendCategory::getDeleted, NOT_DELETE.getKey());
            queryWrapper.orderByDesc(SysBizRecommendCategory::getOrderNum);
            List<SysBizRecommendCategory> list = recommendCategoryService.list(queryWrapper);
            // 返回数据
            return R.ok(list);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取商品推荐分类失败", e);
            return R.fail("获取商品推荐分类失败，请稍后尝试");
        }
    }

    /**
     * 获取销售业务员列表
     */
    @GetMapping("/querySalesUserList")
    public R<List<SysBizUser>> querySalesUserList() {
        try {
            LambdaQueryWrapper<SysBizUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizUser::getTenantId, getTenantId());
            queryWrapper.eq(SysBizUser::getUserRole, 2);
            queryWrapper.eq(SysBizUser::getDeleted, NOT_DELETE.getKey());
            queryWrapper.eq(SysBizUser::getAuthenticationStatus, 1);
            queryWrapper.orderByDesc(SysBizUser::getId);
            List<SysBizUser> list = userService.list(queryWrapper);
            // 返回数据
            return R.ok(list);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取销售业务员列表失败", e);
            return R.fail("获取销售业务员列表失败，请稍后尝试");
        }
    }

    /**
     * 获取素材中心分类(无效)
     *
     * @return 分类列表
     */
    @GetMapping("/queryMaterialCategory")
    public R<List<SysBizMaterialCategory>> queryMaterialCategory() {
        try {
            LambdaQueryWrapper<SysBizMaterialCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizMaterialCategory::getTenantId, getTenantId());
            // 根据ID降序查询
            queryWrapper.orderByDesc(SysBizMaterialCategory::getId);
            List<SysBizMaterialCategory> list = sysBizMaterialCategoryService.list(queryWrapper);
            // 返回数据
            return R.ok(list);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("查询素材中心分类失败", e);
            return R.fail("查询素材中心分类失败，请稍后尝试");
        }
    }

    /**
     * 获取客服问题列表（服务与帮助）
     *
     * @return 客服问题列表
     */
    @GetMapping("/queryServiceQuestion")
    public R<PageResult<SysBizServiceQuestion>> queryServiceQuestion() {
        try {
            startPage();
            LambdaQueryWrapper<SysBizServiceQuestion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizServiceQuestion::getDeleted, NOT_DELETE.getKey());

            queryWrapper.eq(SysBizServiceQuestion::getTenantId, getTenantId());
            queryWrapper.orderByDesc(SysBizServiceQuestion::getOrderNum);
            queryWrapper.orderByDesc(SysBizServiceQuestion::getCreateTime);
            List<SysBizServiceQuestion> sysBizMaterials = serviceQuestionService.list(queryWrapper);
            TableDataInfo dataTable = getDataTable(sysBizMaterials);
            List<?> rows = dataTable.getRows();
            List<SysBizServiceQuestion> collect = rows.stream().map(p -> (SysBizServiceQuestion) p).collect(Collectors.toList());
            return R.ok(new PageResult<>(dataTable.getTotal(), collect));
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取客服问题列表失败", e);
            return R.fail("获取客服问题列表失败，请稍后尝试");
        }
    }

    /**
     * 获取素材(带分页)（无效）
     *
     * @param searchValue 搜索值
     * @param categoryId  分类ID,全部不用传
     * @return 分类列表
     */
    @GetMapping("/queryMaterial")
    public R<PageResult<MaterialVo>> queryMaterial(@RequestParam(required = false, value = "searchValue") String searchValue, @RequestParam(required = false, value = "categoryId") Long categoryId) {
        try {
            startPage();
            LambdaQueryWrapper<SysBizMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizMaterial::getTenantId, getTenantId());
            queryWrapper.eq(SysBizMaterial::getStatus, EnableStatusEnum.ENABLE.getKey());
            queryWrapper.like(StringUtils.isNotBlank(searchValue), SysBizMaterial::getTitle, searchValue);
            queryWrapper.eq(categoryId != null, SysBizMaterial::getCategoryId, categoryId);
            queryWrapper.orderByDesc(SysBizMaterial::getSort);
            queryWrapper.orderByDesc(SysBizMaterial::getCreateTime);
            List<SysBizMaterial> sysBizMaterials = sysBizMaterialService.list(queryWrapper);
            TableDataInfo dataTable = getDataTable(sysBizMaterials);
            List<?> rows = dataTable.getRows();
            ArrayList<MaterialVo> item = new ArrayList<>();
            for (Object row : rows) {
                SysBizMaterial sysBizMaterial = (SysBizMaterial) row;
                MaterialVo target = new MaterialVo();
                BeanUtils.copyProperties(sysBizMaterial, target);
                target.setIsCollection(sysBizProfileService.isCollected(sysBizMaterial.getId(), getUserId(), CollectionTypeEnum.MATERIAL.getKey()));
                item.add(target);
            }
            return R.ok(new PageResult<>(dataTable.getTotal(), item));
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("查询素材中心分类失败", e);
            return R.fail("查询素材中心分类失败，请稍后尝试");
        }
    }

    /**
     * 获取素材详情 （无效）
     *
     * @param id 素材id
     * @return 素材详情
     */
    @GetMapping("/queryMaterialById/{id}")
    public R<MaterialVo> queryMaterialById(@PathVariable Long id) {
        try {
            SysBizMaterial sysBizMaterial = sysBizMaterialService.getById(id);
            MaterialVo target = new MaterialVo();
            BeanUtils.copyProperties(sysBizMaterial, target);
            return R.ok(target);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("查询素材中心详情失败", e);
            return R.fail("查询素材中心详情失败，请稍后尝试");
        }
    }

    /**
     * 获取站点支付方式开关数据
     *
     * @return 数据
     */
    @GetMapping("/queryTenantPay")
    public R<TenantPayVo> queryTenantPay() {
        TenantPayVo vo = new TenantPayVo();
        try {
            SysBizTenant bizTenant = tenantService.getOne(new LambdaQueryWrapper<SysBizTenant>().eq(SysBizTenant::getId, getTenantId()));
            if(bizTenant != null){
                vo.setPayType(bizTenant.getPayType());
            }
            return R.ok(vo);
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("获取站点支付方式开关数据失败", e);
            return R.fail("获取站点支付方式开关数据失败，请稍后尝试");
        }
    }

}
